<template>
    <el-drawer width="20vw" class="flex-drawer" direction="rtl" :close-on-click-modal="false" v-model="info.visible" @close="handleClose"  >
        <template #header>
            <div style="font-size:var(--18FontSize); font-weight:500; color:#525866;">{{ info.forEdit ? `编辑巡检对象模板(${info.row.templateCode})` : '新增巡检对象模板' }}</div>
        </template>
        <el-form class="flex-form" ref="myForm" :model="form" :rules="rules" label-position="top">
            <el-form-item label="名称" prop="templateName">
                <FlexInput :data="{ paramKey:'templateName' }" :form="form" />
            </el-form-item>
            <el-form-item label="标签" prop="labelId">
                <FlexSelect :payload="labelList" :data="{ paramKey:'labelId', fullWidth:true, labelKey:'labelId', labelName:'labelName' }" :form="form" />
            </el-form-item>
            <el-form-item v-if="form.labelId === 1 " label="关联设备类型">
                <FlexSelect :payload="meterTypeList" :data="{ paramKey:'equipmentType', fullWidth:true, hasSearch:true, searchType:'local', labelKey:'typeId', labelName:'typeName' }" :form="form" />
            </el-form-item>
            <el-form-item label="检查方式" prop="checkWay">
                <el-radio-group v-model="form.checkWay">
                    <el-radio value="1">
                        <template #default>
                            <div style="display:flex;align-items: center;">
                                <div style="margin-right:var(--sPadding);">抽查</div>
                                <el-input 
                                    style="margin-right:var(--sPadding);"
                                    :class="{ 
                                        'flex-input':true,
                                        isError:errorMsg.isError && form.checkWay === '1' , 
                                        notNum:errorMsg.errorType === 'notNum' && form.checkWay === '1',
                                        notPosInt:errorMsg.errorType === 'notPosInt' && form.checkWay === '1' 
                                    }"
                                    v-model="form.checkRatio" 
                                    @input="handleCheckNum" 
                                    @focus="()=>handleFocus('1')"
                                >
                                    <template #suffix>%</template>
                                </el-input>
                                <el-tooltip content="按比例随机抽查" effect="light"> <i class="ri-information-fill"></i></el-tooltip>
                            </div>
                        </template>
                    </el-radio>
                    <el-radio value="2">
                        <template #default>
                            <div style="display:flex; align-items: center;">
                                <div style="margin-right:var(--sPadding);">循环抽查</div>
                                <el-input 
                                    style="margin-right:var(--sPadding);"
                                    :class="{ 
                                        'flex-input':true, 
                                        isError:errorMsg.isError && form.checkWay === '2', 
                                        notNum:errorMsg.errorType === 'notNum' && form.checkWay === '2',
                                        notPosInt:errorMsg.errorType === 'notPosInt' && form.checkWay === '2'
                                    }"
                                    v-model="form.circleCheckRatio" 
                                    @input="handleCheckNum" 
                                    @focus="()=>handleFocus('2')"
                                >
                                    <template #suffix>%</template>
                                </el-input>
                                <el-tooltip content="按比例从未检查或检查次数少的对象中循环抽查" effect="light"> <i class="ri-information-fill"></i></el-tooltip>
                            </div>
                        </template>
                    </el-radio>
                    <el-radio value="0">全部检查</el-radio>
                </el-radio-group>
            </el-form-item>   
        </el-form>
        <div style="display:flex; gap:var(--mPadding); margin-top:var(--lPadding); ">
            <div class="flex-btn middle opacity" style="flex:1;" @click="handleClose">取消</div>
            <div class="flex-btn middle" style="flex:1;" @click="handleSubmit">确认</div>
        </div>
    </el-drawer>
</template>

<script setup>
    import { watch, ref, reactive, nextTick, onUnmounted, onMounted } from 'vue';
    import { addOrUpdateTpl, getMeterTypeList, getTplCode } from '@/api/tpl.js';
    import FlexInput from '@/components/FlexInput.vue';
    import FlexSelect from '@/components/FlexSelect.vue';
    import { ElMessage } from 'element-plus';
    const props = defineProps({
        info:{ type:Object },
        labelList:{ type:Array },
        meterTypeList:{ type:Array }
    });
    const emit = defineEmits(['update:info', 'refresh']);
    const myForm = ref(null);
    const form = reactive({
        templateName:'',
        labelId:'',
        equipmentType:'',
        checkWay:'',
        checkRatio:null,
        circleCheckRatio:null,
    });
    // 标记内部控件的验证状态
    const errorMsg = ref({ isError:false, errorType:'' });
    const rules = reactive({
        templateName:[{ required:true, message:'名称不能为空',  trigger:'blur' }],
        labelId:[{ required:true, message:'请选择标签',  trigger:'blur' }],
        checkWay:[{ required:true, message:'请选择检查方式',  trigger:'blur' }],
    });
    //
    function handleFocus(val){
        form.checkWay = val;
        // 聚焦时直接设置当前单选框组件的值
        nextTick(()=>{
            // 判断切换时，重新验证一遍，
            let _val = form.checkWay === '1' ? form.checkRatio : form.circleCheckRatio;
            if ( _val ) {
                handleCheckNum(_val);
            }
        })
    }
    // 验证抽查比例
    function handleCheckNum(val){
        let _val = +val;
        if ( isNaN(val) ) {
            errorMsg.value = { isError:true, errorType:'notNum' };
            if ( form.checkWay === '1') {
                form.checkRatio = null;
            }
            if ( form.checkWay === '2') {
                form.circleCheckRatio = null;
            } 
            return;
        }
        if ( _val > 0 && _val <= 100 && Number.isInteger(_val) ) {
            errorMsg.value = { isError:false, errorType:'' };
        } else {
            errorMsg.value = { isError:true, errorType:'notPosInt' };
            if ( form.checkWay === '1') {
                form.checkRatio = null;
            }
            if ( form.checkWay === '2') {
                form.circleCheckRatio = null;
            } 
        }
    }
   
    // 重置状态
    function handleClose(){
        Object.keys(form).forEach(key=>{
            form[key] = ''
        });
        myForm.value.clearValidate();
        errorMsg.value = { isError:false, errorType:'' };
        props.info.visible = false;
    }
    watch(()=>props.info, ()=>{
        // 编辑模式，填充表单
        if ( props.info.forEdit ) {
            let { templateName, labelId, checkWay, checkValue, equipmentType } = props.info.row;
            form.templateName = templateName;
            form.labelId = labelId;
            form.equipmentType = equipmentType;
            form.checkWay = String(checkWay);
            if ( form.checkWay === '1') {
                form.checkRatio = checkValue;
            }
            if ( form.checkWay === '2') {
                form.circleCheckRatio = checkValue;
            }
        }
        
    })
    function handleSubmit(){
        myForm.value.validate(valid=>{
            if ( valid ){
                // 判断errorMsg是否存在
                if ( form.checkWay === '0') {
                    errorMsg.value = { isError:false, errorType:'' };
                }
                if ( form.checkWay === '1' || form.checkWay === '2') {
                    let _val = form.checkWay === '1' ? form.checkRatio : form.circleCheckRatio;
                    handleCheckNum(_val);
                }
                if ( !errorMsg.value.isError ) {
                    let obj = {
                        templateName:form.templateName,
                        labelId:form.labelId,
                        checkWay:form.checkWay
                    };
                    if ( form.labelId === 1){
                        obj.equipmentType = form.equipmentType
                    }
                    let _val = form.checkWay === '1' ? form.checkRatio : form.checkWay === '2' ? form.circleCheckRatio : 0
                    if ( form.checkWay === '1' ) {
                        obj.checkValue = form.checkRatio;
                    }
                    if ( form.checkWay === '2' ) {
                        obj.checkValue = form.circleCheckRatio;
                    }
                    if ( props.info.forEdit ) {
                        obj.templateCode = props.info.row.templateCode;
                    }
                    const promise = props.info.forEdit ? Promise.resolve() : new Promise((resolve, reject)=>{
                        getTplCode()
                        .then(res=>{
                            if ( res.data.code === 200 ) {
                                resolve(res.data.data);
                            }
                        })
                    });
                    promise
                    .then((code)=>{
                        if ( code ) obj['templateCode'] = code;
                        addOrUpdateTpl(obj, props.info.forEdit)
                        .then(res=>{
                            if ( res.data.code === 200 ) {
                                ElMessage({
                                    type:'success',
                                    message:`${props.info.forEdit ? '更新' : '新增'}巡检对象模板成功`
                                });
                                handleClose();
                                emit('refresh');
                            }
                        })                                   
                    })
                    
                }
                
            }
        })
    }
    
</script>

<style lang="scss">
    
</style>